/**
 * This file is part of AppStoreBot.
 *
 *  AppStoreBot is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AppStoreBot is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AppStoreBot.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package lu.pragmaconsult.appstorebot.itunes;

import java.io.InputStream;

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * TODO: Type comment
 * @author Wilfried Vandenberghe (wilfried.vandenberghe at pragmaconsult.lu)
 */
class HtmlParser {

	private final static XPath XPATH = XPathFactory.newInstance().newXPath();
	
	private Document doc;
	
	/**
	 * 
	 * @param stream
	 * @throws Exception
	 */
	public HtmlParser(InputStream stream) throws Exception {
		InputSource source = new InputSource(stream);
		DOMParser parser = new DOMParser();

			try {
				parser.parse(source);
			} catch (SAXException e) {
				throw new Exception(e);
			}
			
			doc = parser.getDocument();
	}
	
	private XPathExpression compile(String pattern) throws Exception {
		try {
			return XPATH.compile(pattern);
		} catch (XPathExpressionException e) {
			throw new Exception(e);
		}
	}
	
	/**
	 * 
	 * @param pattern
	 * @param constant
	 * @return
	 * @throws Exception
	 */
	public Object evaluate(String pattern, QName constant) throws Exception {
		XPathExpression expression = compile(pattern);

		try {
			return expression.evaluate(doc, constant);
		} catch (XPathExpressionException e) {
			throw new Exception(e);
		}
	}
	
	/**
	 * 
	 * @return
	 */
	Document getDocument() {
		return doc;
	}
}
